package handler

import (
	"context"
	"lab-service/post/model"
	pm "lab-service/proto/message"
)

type Message struct{}

func (m *Message) One(ctx context.Context, req *pm.MessageRequest, rsp *pm.MessageResponse) error {
	// model Message -> mm
	mm := &model.Message{
		Id: req.Id,
	}

	if err := mm.OneById(); err != nil {
		return err
	}

	rsp.Msg = &pm.OneMessage{
		Id:        mm.Id,
		Enable:    mm.Enable,
		Public:    mm.Public,
		CreatedAt: mm.CreatedAt.Unix(),
		Title:     mm.Title,
		Content:   mm.Content,
		Author:    mm.Author,
		Uid:       mm.Uid,
	}

	return nil
}

func (m *Message) Page(ctx context.Context, req *pm.MessageRequest, rsp *pm.MessageResponse) error {
	// model Message -> mm
	mm := &model.Message{
		Enable: req.Enable,
		Uid:    req.Uid,
		Public: req.Public,
	}

	ms, err := mm.Page(req.PageNum, req.PageSize, req.Desc, req.Order)
	if err != nil {
		return err
	}

	for _, m := range ms {
		rsp.Msgs = append(rsp.Msgs, &pm.OneMessage{
			Id:        m.Id,
			CreatedAt: m.CreatedAt.Unix(),
			Title:     m.Title,
			Content:   m.Content,
			Author:    m.Author,
			Public:    m.Public,
			Uid:       m.Uid,
			Enable:    m.Enable,
		})
	}

	rsp.Total, err = mm.Count()
	if err != nil {
		return err
	}

	rsp.PageSize = req.PageSize
	rsp.PageNum = req.PageNum

	return nil
}

func (m *Message) Create(ctx context.Context, req *pm.MessageRequest, rsp *pm.MessageResponse) error {
	// model Message -> mm
	mm := &model.Message{
		Uid:     req.Uid,
		Public:  req.Public,
		Title:   req.Title,
		Content: req.Content,
		Enable:  true,
		Author:  req.Author,
	}

	if err := mm.Create(); err != nil {
		return err
	}

	return nil
}

func (m *Message) CountMe(ctx context.Context, req *pm.MessageRequest, rsp *pm.MessageResponse) error {
	// model Message -> mm
	mm := &model.Message{
		Uid: req.Uid,
	}

	total, err := mm.Count()
	if err != nil {
		return err
	}

	rsp.Total = total

	return nil
}

func (m *Message) Toggle(ctx context.Context, req *pm.MessageRequest, rsp *pm.MessageResponse) error {
	// model Message -> mm
	mm := &model.Message{
		Id: req.Id,
	}

	if err := mm.OneById(); err != nil {
		return err
	}

	if err := mm.Toggle(); err != nil {
		return err
	}

	return nil
}
